import { createRouter, createWebHistory } from 'vue-router'
import { localCache } from '@/utils/cache'
import { TOKEN } from '@/global/constans'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: '/layout'
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import("@/views/layout/index.vue"),
    children: [
      {
        path: '/layout/homePage',
        name: 'home',
        component: () => import("@/views/HomePage/HomePage.vue")
      },
    ]
  }, {
    path: '/login',
    name: 'login',
    component: () => import("@/views/login/login.vue")
  },
  {
    path: '/:pathMatch(.*)',
    name: '404',
    component: () => import("@/views/error/404.vue")
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const token = localCache.getCache(TOKEN);
  if (!token && to.path == '/layout') {
    next('/login')
  }
  if (to.path == "/layout") {
    next('/layout/homePage')
  }
  next()
})

export default router
